package app.dws;

import app.dwd.BaseAppFollowV2;

import static common.Constant.*;

import bean.VisitorStats;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.apache.logging.log4j.util.Strings;
import util.GmallSinkUtil;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.HashMap;

public class DWSVistitorStatsAppFollow extends BaseAppFollowV2 {

    public static void main(String[] args) {
        new DWSVistitorStatsAppFollow().init(4141,
                                             1,
                                             "DWSVistitorStatsAppFollow",
                                             "DWSVistitorStatsAppFollow",
                                             TOPIC_DWD_PAGE_LOG,
                                             TOPIC_DWM_UV,
                                             TOPIC_DWM_USER_JUMP_DETAIL);
    }

    @Override
    public void run(StreamExecutionEnvironment env, HashMap<String, DataStreamSource<String>> streamKafkaSourceMap) {
        //1. pojo解析各流并union
        DataStream<VisitorStats> visitorStatsStream = parseAndUnion(streamKafkaSourceMap);

        //2. 分组开窗聚合
        SingleOutputStreamOperator<VisitorStats> visitorStatsAggStream = aggregateVisitorStats(visitorStatsStream);
        visitorStatsAggStream.print();
        //3.写入clickhouse
        sendToClickHouse(visitorStatsAggStream);

    }

    private void sendToClickHouse(SingleOutputStreamOperator<VisitorStats> visitorStatsAggStream) {
        visitorStatsAggStream.addSink(GmallSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DATABASE, Constant.CLICKHOUSE_VISITOR_STATS_2021, VisitorStats.class));
    }

    private SingleOutputStreamOperator<VisitorStats> aggregateVisitorStats(DataStream<VisitorStats> visitorStatsStream) {
        return visitorStatsStream
            .keyBy(obj -> obj.getVc() + "_" + obj.getCh() + "_" + obj.getAr() + "_" + obj.getIs_new())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(new ReduceFunction<VisitorStats>() {
                @Override
                public VisitorStats reduce(VisitorStats value1, VisitorStats value2) throws Exception {
                    value1.setSv_ct(value1.getSv_ct() + value2.getSv_ct());
                    value1.setUj_ct(value1.getUj_ct() + value2.getUj_ct());
                    value1.setPv_ct(value1.getPv_ct() + value2.getPv_ct());
                    value1.setUv_ct(value1.getUv_ct() + value2.getUv_ct());
                    value1.setDur_sum(value1.getDur_sum() + value2.getDur_sum());
                    return value1;
                }
            }, new ProcessWindowFunction<VisitorStats, VisitorStats, String, TimeWindow>() {
                @Override
                public void process(String s, Context ctx, Iterable<VisitorStats> elements, Collector<VisitorStats> out) throws Exception {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String stt = simpleDateFormat.format(ctx.window().getStart());
                    String edt = simpleDateFormat.format(ctx.window().getEnd());
                    VisitorStats visitorStats = elements.iterator().next();
                    visitorStats.setStt(stt);
                    visitorStats.setEdt(edt);
                    out.collect(visitorStats);
                }
            });
    }

    private DataStream<VisitorStats> parseAndUnion(HashMap<String, DataStreamSource<String>> streamKafkaSourceMap) {
        DataStreamSource<String> pageStream = streamKafkaSourceMap.get(TOPIC_DWD_PAGE_LOG);
        DataStreamSource<String> uvStream = streamKafkaSourceMap.get(TOPIC_DWM_UV);
        DataStreamSource<String> jumpStream = streamKafkaSourceMap.get(TOPIC_DWM_USER_JUMP_DETAIL);
        //pv,连续访问时长
        SingleOutputStreamOperator<VisitorStats> pvAndDurationTimeStream = pageStream
            .map(s -> {
                JSONObject jsonObject = JSON.parseObject(s);
                JSONObject common = jsonObject.getJSONObject("common");
                JSONObject page = jsonObject.getJSONObject("page");
                return new VisitorStats(
                    "",
                    "",
                    common.getString("vc"),
                    common.getString("ch"),
                    common.getString("ar"),
                    common.getString("is_new"),
                    0L, 1L, 0L, 0L,
                    page.getLong("during_time"),
                    jsonObject.getLong("ts"));
            })
            .assignTimestampsAndWatermarks(WatermarkStrategy
                                               .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                               .withTimestampAssigner((obj, ts) -> obj.getTs()));


        //uv
        SingleOutputStreamOperator<VisitorStats> UVStatsStream = uvStream
            .map(s -> {
                JSONObject jsonObject = JSON.parseObject(s);
                JSONObject common = jsonObject.getJSONObject("common");
                return new VisitorStats(
                    "",
                    "",
                    common.getString("vc"),
                    common.getString("ch"),
                    common.getString("ar"),
                    common.getString("is_new"),
                    1L, 0L, 0L, 0L,
                    0L,
                    jsonObject.getLong("ts"));
            })
            .assignTimestampsAndWatermarks(WatermarkStrategy
                                               .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                               .withTimestampAssigner((obj, ts) -> obj.getTs()));

        //uv
        SingleOutputStreamOperator<VisitorStats> jumpStatsStream = jumpStream
            .map(s -> {
                JSONObject jsonObject = JSON.parseObject(s);
                JSONObject common = jsonObject.getJSONObject("common");
                return new VisitorStats(
                    "",
                    "",
                    common.getString("vc"),
                    common.getString("ch"),
                    common.getString("ar"),
                    common.getString("is_new"),
                    0L, 0L, 0L, 1L,
                    0L,
                    jsonObject.getLong("ts"));
            })
            .assignTimestampsAndWatermarks(WatermarkStrategy
                                               .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                               .withTimestampAssigner((obj, ts) -> obj.getTs()));

        //sv:进入次数
        SingleOutputStreamOperator<VisitorStats> svStatsStream = pageStream
            .flatMap(new FlatMapFunction<String, VisitorStats>() {
                @Override
                public void flatMap(String value, Collector<VisitorStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    JSONObject page = obj.getJSONObject("page");
                    if (Strings.isEmpty(page.getString("last_page_id"))) {
                        JSONObject common = obj.getJSONObject("common");
                        out.collect(new VisitorStats(
                            "",
                            "",
                            common.getString("vc"),
                            common.getString("ch"),
                            common.getString("ar"),
                            common.getString("is_new"),
                            0L, 0L, 1L, 0L,
                            0L,
                            obj.getLong("ts"))
                        );
                    }
                }
            }).assignTimestampsAndWatermarks(WatermarkStrategy
                                                 .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                                 .withTimestampAssigner((obj, ts) -> obj.getTs()));

        return pvAndDurationTimeStream.union(UVStatsStream, jumpStatsStream, svStatsStream);
    }

}




























